package com.xing.oauth.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.xing.oauth.common.exception.TokenException;
import com.xing.oauth.common.response.ResultCode;
import com.xing.oauth.service.OAuthService;
import com.xing.oauth.service.Oauth2ClientService;
import com.xing.oauth.util.DaikinStaticWebUrl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;




@Controller
public class AuthorizeController  extends BaseController {
    protected static final Logger logger = LoggerFactory.getLogger(AuthorizeController.class);


    //@Autowired
    @Resource
    private OAuthService oAuthService;

    @Autowired
    private Oauth2ClientService clientService;

    @Autowired
    private DaikinStaticWebUrl daikinStaticWebUrl;




    @RequestMapping("/authorize")
    public Object authorize(Model model, HttpServletRequest request) throws OAuthProblemException, OAuthSystemException {

        try {
            //构建OAuth授权请求
            OAuthAuthzRequest oAuthAuthzRequest = new OAuthAuthzRequest(request);

            //校验传入的客户端的id是否正确
            if (!oAuthService.checkClientId(oAuthAuthzRequest.getClientId())) {
                //                OAuthASResponse
                //                        .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                //                        .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                //                        .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                //实际做项目改了
                throw new TokenException(ResultCode.CLIENT_CHECKING_FAIL);
            }

            Subject subject = SecurityUtils.getSubject();

            //如果用户没有登录，跳转到登录页面
            if (!subject.isAuthenticated()) {
                //登录失败时跳转到登录页面
                if (!login(subject, request)) {
                    //登录失败后，跳转到登录页面
                    return "redirect:/login.html?client_id=" + oAuthAuthzRequest.getClientId() + "&redirect_uri="
                            + oAuthAuthzRequest.getRedirectURI() + "&response_type=" + oAuthAuthzRequest.getResponseType()
                            + "&state=" + oAuthAuthzRequest.getState() + "userAgreement=" + daikinStaticWebUrl.getUserAgreement()
                            + "&privatePolicy" + daikinStaticWebUrl.getPrivatePolicy();
                }
            }
            //返回响应体，头部为空，状态码为200
            return new ResponseEntity(null, HttpStatus.valueOf(200));
        } catch (OAuthProblemException e) {
            logger.error("授权码获取失败");
            e.printStackTrace();
            throw new TokenException(ResultCode.EXPIRED_ACCESSTOKEN_CREDENTIAL);

        }

        /**
         * 以后遇见一个看接口的事情，要是有时间的话，直接起一个项目，把接口的代码，直接敲出来，应该会有点用吧。
         */

    }

    /**
     * 校验用户是否登录
     *
     * @param subject
     * @param request
     * @return
     */
    private boolean login(Subject subject, HttpServletRequest request) {
        //不能为get请求登录，需要post
        String method = "get";
        if (method.equalsIgnoreCase(request.getMethod())) {
            return false;
        }
        //请求里面获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判断是否为空，这个很重要，虽然是模板
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return false;
        }
        //根据用户名和密码生成token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            return true;
        } catch (Exception e) {
            request.setAttribute("error", "登录失败：" + e.getClass().getName());
            return false;
        }

    }


}
